import { useStore as useUserStore } from "@/store/user";
import jwtSign from "@/common/jwt";
import { message, Modal } from "ant-design-vue";
import _ from "lodash";
import router from "@/router";
import eventBus from "@/common/mitt";
let logout_num = 0;
// 退出登录
const logout = _.debounce(() => {
  if (logout_num > 0) {
    return;
  }
  logout_num = 1;
  Modal.error({
    title: '提示',
    content: '登录已失效请重新登录',
    okText: '确认',
    onOk: () => {
      const userStore = useUserStore();
      userStore.logout();
      eventBus.loginLose.emit();
    },
  })
}, 5000, { leading: true, trailing: false })

export default class apibase {
  constructor() {

  }
  // api请求公共方法
  base(instance: any, mock: boolean) {
    instance.defaults.baseURL = mock ? '/mock' : process.env.VUE_APP_BASE_API;
    console.log(instance.defaults.baseURL)
    instance.defaults.withCredentials = true;
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 请求拦截添加公共参数
     */
    instance.interceptors.request.use((config: any) => {
      config.timeout = 3000000;
      return config;
    })
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 回传拦截处理回传内容
     */
    instance.interceptors.response.use((response: any) => {
      let res = { code: response.data.code, msg: response.data.msg, data: response.data.data };
      return this.matchRes(res);
    }, (error: any) => {
      error = JSON.parse(JSON.stringify(error));
      if (error?.response) {
        console.error(error);
      } else {
        message.error(error.message);
      }
      return Promise.reject(error);
    })
  }
  // res 回传结果, async 是否异步
  matchRes = (res: any, async: Boolean = true) => {

    if (res.code === 200) {
      return res;
    } else if (res.code === 401) {
      logout();
      return async ? Promise.reject(res) : res;
    } else if (res.code === 400) {
      message.error(res.msg);
      return async ? Promise.reject(res) : res;
    } else if (res.code === 403) {
      message.error(res.msg);
      return async ? Promise.reject(res) : res;
    } else if (res.code === 500) {
      return async ? Promise.reject(res) : res;
    } else {
      return async ? Promise.reject(res) : res;
    }
  }
  //type: jwt验签请求   upload:上传
  get({ url, instance, data, type = "jwt", mock = false }: { url: string, instance: any, data: any, type?: string, mock?: boolean }) {
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.token || '';
        const uid = userStore.uid || '';
        let Authorization: any = {
          iat: (new Date().getTime() / 1000).toFixed(0),
          token,
          uid,
          ...data,
        };
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance, mock);
    return instance.get(url, { params: data });
  }
  //type: jwt验签请求   upload:上传
  post({ url, instance, data, type = "jwt", mock = false, withoutSignData, formData }: { url: string, instance: any, data: any, type?: string, mock?: boolean, withoutSignData?: any, formData?: any }) {
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.token || '';
        const uid = userStore.uid || '';
        let Authorization: any = {
          iat: (new Date().getTime() / 1000).toFixed(0),
          token,
          uid,
          ...data,
        };
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance, mock);
    if (formData) {
      return instance.post(url, formData);
    } else {
      return instance.post(url, { ...data, ...withoutSignData });
    }
  }
}